package cn.shaines.filesystem.util;

import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Scanner;

@Component
public class VHostUtil {
    /**
     * 文本文件中追加一行数据
     * @param filePath
     * @param data
     */
    public static void appendToFile(String filePath, String data) {
        try {
            Path path = Paths.get(filePath);
            Files.write(path, data.getBytes(), StandardOpenOption.APPEND);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据行号，删除某一行文本
     * @param filePath
     * @param lineNumber
     */
    public static void deleteByLineNum(String filePath, int lineNumber) {
        Path path = Paths.get(filePath);
        try {
            List<String> allLines = Files.readAllLines(path);

            // 移除指定的行号
            allLines.remove(lineNumber - 1);

            // 将剩余的行写回文件
            Files.write(path, allLines);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据文本搜索所在行号
     * @param filePath
     * @param searchText
     * @return
     */
    public static int findLineNumByText(String filePath, String searchText) {
        int lineNumber = 1;
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains(searchText)) {
                    return lineNumber;
                }
                lineNumber++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1; // Not found
    }

    /**
     * 根据查询的文本，删除该文本行
     * @param filePath 要查找的文本路径
     * @param searchText 查找的文本内容
     * @return
     */
    public static boolean deleteByText(String filePath, String searchText)  {
        boolean flag =false;
        int lineNumbers=findLineNumByText(filePath,searchText);
        if(lineNumbers!=-1) {
            deleteByLineNum(filePath, lineNumbers);
            flag=true;
        }

        return flag;
    }

    /**
     *
     * @param filePath 文件路径
     * @param searchText 要查找的文本
     * @param isComment 是否注释：true增加#，false去掉#
     * @return
     */
    public static boolean commentOutText(String filePath,String searchText,boolean isComment) {
        boolean flag =false;
        try (Scanner scanner = new Scanner(new FileReader(filePath));
             FileWriter writer = new FileWriter(filePath + ".tmp")) {

            boolean found = false;
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if (!found && line.contains(searchText)) {
                    if(isComment){
                        line = "#" + line; // 在行首添加#进行注释
                    }else{
                        if(line.startsWith("#")){
                            line=line.substring(1);
                        }
                    }
                    found = true;
                }
                writer.write(line + System.lineSeparator());
            }

            if (found) {
                // 删除原文件，重命名临时文件
                File originalFile = new File(filePath);
                File commentedFile = new File(filePath + ".tmp");
                originalFile.delete();
                commentedFile.renameTo(originalFile);
                flag=true;
            } else {
                // 没有找到文本，删除临时文件
                File tmpFile = new File(filePath + ".tmp");
                tmpFile.delete();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }
    public static void main(String[] args) {
        String filePath = VHostUtil.class.getClassLoader().getResource("VHOST.properties").getPath();
        String dataToAppend = "新增的数据行;";
//        appendToFile(filePath, dataToAppend);
//        System.out.println(commentOutText(filePath,dataToAppend,false));
        System.out.println(deleteByText(filePath,dataToAppend));

    }
}
